package com.zm.vcode.web;

import com.zm.vcode.bean.Result;
import com.zm.vcode.bean.VcodeProperties;
import com.zm.vcode.util.VerifyCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@RestController
@RequestMapping("vcode")
public class VcodeDo {
    @Autowired
    VcodeProperties properties;

    @RequestMapping("props")
    public VcodeProperties properties(){
        return properties;
    }

    @RequestMapping(value = "image",
    produces = MediaType.IMAGE_JPEG_VALUE)
    public void image(HttpServletResponse resp, HttpSession session) throws IOException {
        String vcode = VerifyCodeUtils.outputImage(resp);
        session.setAttribute("vcode",vcode);
    }

    @RequestMapping("email")
    public Result email(String email,String title,HttpSession session){
        String content = properties.getMsgs()
                .stream()
                .filter(m->m.get("title").equals(title))
                .findFirst()
                .get()
                .get("content");
        String vcode = "" + System.currentTimeMillis();
        vcode = vcode.substring(vcode.length() - 4);
        session.setAttribute("vcode",vcode);
        content += vcode;
        sendSimpleMail(email,title,content);
        return new Result(1,"验证码发送至邮箱：" + email,null);
    }


     @Autowired
     private JavaMailSender mailSender;

     public void sendSimpleMail(String to, String subject, String content) {
         SimpleMailMessage message = new SimpleMailMessage();
         message.setFrom(properties.getFrom());
         message.setTo(to);
         message.setSubject(subject);
         message.setText(content);
         mailSender.send(message);
     }

}
